<?php

/**
 * 文章tag标签管理
 * @author  xiaobai
 * @date    2018-01-28
 */

namespace app\panel\controller;

use app\common\controller\Panelbase;
use app\common\model\Tag;
use app\common\model\TagData;

class Tags extends Panelbase
{
    public function initialize()
    {
        parent::initialize();
        $this->model    = new Tag();
        $this->tag_data = new TagData();

        $this->assign('types', $this->model->getType());
    }

    public function index()
    {
        $list  = $this->model->order('id desc')->paginate(config('other.page_num'));

        $this->assign("list", $list);
        return $this->fetch();
    }

    // 删除推荐位和对应的内容
    public function delete()
    {
        $id = input("param.id", 0, 'intval');
        if (empty($id) || !is_numeric($id)) {
            $this->error('参数错误');
        }

        $this->model->startTrans();

        $del_res = $this->model->where(['id'=>$id])->delete();
        if ($del_res === false) {
            $this->model->rollback();
            $this->error('删除Tag标签失败');
        }

        $tag_del = $this->tag_data->where(['tag_id'=>$id])->delete();
        if ($tag_del === false) {
            $this->model->rollback();
            $this->error('删除Tag标签数据失败');
        }

        $this->model->commit();
        $this->success('删除成功');
    }

    /**
     * 标签文章列表
     * @return mixed
     */
    public function newslist()
    {
        $tag_id = input('param.tagId');

        // 标签信息
        $tag_info = $this->model->where(['id'=>$tag_id])->find();

        // 推荐的内容信息
        $tag_where     = ['a.tag_id'=>$tag_id];
        $tag_filed     = 'a.id,a.data_id,a.type,b.title,b.status';
        $tag_data_list = $this->tag_data->field($tag_filed)
                                        ->alias('a')
                                        ->join('__NEWS__ b', 'a.data_id = b.id')
                                        ->where($tag_where)
                                        ->order('a.id desc')
                                        ->paginate(config('other.page_num'));

        $this->assign("list", $tag_data_list);
        $this->assign('info', $tag_info);
        return $this->fetch();
    }

    /**
     * 移除推荐位里的文章
     */
    public function remove()
    {
        $id = input("param.id", 0, 'intval');
        if (empty($id) || !is_numeric($id)) {
            $this->error('参数错误');
        }
        $res = $this->tag_data->where(array('id'=>$id))->delete();
        if ($res !== false) {
            $this->success('移除成功');
        } else {
            $this->error('移除失败');
        }
    }

}
